import 'package:flutter/foundation.dart';
import 'dart:developer' as developer;
import 'package:sqflite/sqflite.dart';
import '../models/period_model.dart';
import '../utils/date_utils.dart';
import 'shared_preferences_service.dart';
import 'error_handler.dart';
import '../utils/errors.dart';
import 'prediction_service.dart';
import '../di/service_locator.dart';
import 'database_helper.dart';


class DataService {
  static final DataService _instance = DataService._internal();
  final SharedPreferencesService _prefsService = SharedPreferencesService();
  final ErrorHandler _errorHandler = ServiceLocator().get<ErrorHandler>();
  final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
  
  static const int _maxRetries = 3;
  
  factory DataService() => _instance;
  
  DataService._internal() {
    _prefsService.initialize();
  }
  
  
  String formatDate(DateTime date) => DateUtils.formatDate(date);
  
  
  Future<void> _updateLastPeriodDateIfNeeded(DateTime periodDate) async {
    final userProfile = await loadUserProfile();
    if (userProfile != null && periodDate.isAfter(userProfile.lastPeriodDate)) {
      final updatedProfile = userProfile.copyWith(lastPeriodDate: periodDate);
      await saveUserProfile(updatedProfile);
    }
  }
  
  
  Future<void> _processPeriodRecordsBatch(List<PeriodModel> records) async {
    if (records.isEmpty) return;
    
    
    final periodRecords = records.where((r) => r.isPeriod).toList();
    if (periodRecords.isEmpty) return;
    
    
    final latestPeriod = periodRecords.reduce((a, b) => 
      a.date.isAfter(b.date) ? a : b
    );
    
    
    await _updateLastPeriodDateIfNeeded(latestPeriod.date);
  }

  
  Future<void> initialize() async {
    try {
      
      await _databaseHelper.database;
      debugPrint('DataService initialized successfully');
      
      
    } catch (e) {
      
      try {
          // 重新初始化数据库的替代方案：关闭并重新打开
          await _databaseHelper.close();
          await _databaseHelper.database;
          debugPrint('Database reinitialized after initialization failure');
        } catch (reInitError) {
        // 创建可恢复的数据库错误
          final appError = AppError(
            message: '初始化数据服务失败',
            type: AppErrorType.database,
            cause: reInitError,
            isRecoverable: true
          );
        appError.retryCallback = initialize;
        _errorHandler.handleError(appError, 'DataService.initialize');
        throw appError;
      }
    }
  }

  
  Future<void> reinitializeDatabase() async {
    try {
      // 重新初始化数据库的替代方案：关闭并重新打开
      await _databaseHelper.close();
      await _databaseHelper.database;
      debugPrint('Database reinitialized successfully');
    } catch (e) {
      final error = _errorHandler.createDatabaseError('重新初始化数据库失败');
      _errorHandler.handleError(error, 'DataService.reinitializeDatabase');
      rethrow;
    }
  }

  
  Future<bool> checkDatabaseStructure() async {
    try {
      final db = await _databaseHelper.database;
      
      final tableInfo = await db.rawQuery(
        "PRAGMA table_info(${DatabaseHelper.tableUser})"
      );
      
      final hasHealthConditionsColumn = tableInfo.any((column) => 
        column['name'] == 'healthConditions'
      );
      
      if (!hasHealthConditionsColumn) {
        debugPrint('Database table is missing required columns');
        return false;
      }
      
      debugPrint('Database structure is valid');
      return true;
    } catch (e) {
      debugPrint('Database structure check failed: $e');
      return false;
    }
  }

  
  Future<T> _withRetry<T>(Future<T> Function() operation, [String operationName = 'operation']) async {
    int attempts = 0;
    Exception? lastException;
    
    while (attempts < _maxRetries) {
      try {
        return await operation();
      } catch (e) {
        lastException = e as Exception;
        attempts++;
        debugPrint('$operationName failed (attempt $attempts/$_maxRetries): $e');
        
        if (attempts < _maxRetries) {
          
          await Future.delayed(Duration(milliseconds: 100 * attempts));
        }
      }
    }
    
    debugPrint('$operationName failed after $_maxRetries attempts');
    throw lastException!;
  }

  
  Future<UserProfile?> loadUserProfile() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final profileData = _prefsService.getObject(SharedPreferencesService.keyUser);
        final profile = profileData != null ? UserProfile.fromMap(profileData) : null;
        debugPrint(profile != null ? 'User profile loaded successfully from SharedPreferences' : 'No user profile found in SharedPreferences');
        return profile;
      }, 'loadUserProfile'),
      'DataService.loadUserProfile',
      fallbackValue: () => null,
      rethrowError: false
    );
  }
  
  // 保持与现有代码的兼容性
  Future<UserProfile?> getUserProfile() async {
    return loadUserProfile();
  }

  
  Future<void> saveUserProfile(UserProfile profile) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final profileMap = profile.toMap();
        if (profileMap['id'] == null) {
          profileMap['id'] = DateTime.now().millisecondsSinceEpoch.toString();
        }
        await _prefsService.setObject(SharedPreferencesService.keyUser, profileMap);
        debugPrint('User profile saved successfully to SharedPreferences');
      }, 'saveUserProfile'),
      'DataService.saveUserProfile',
      rethrowError: true
    );
  }

  
  Future<List<PeriodModel>> loadPeriodRecords() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final recordsData = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
        final records = recordsData.map((data) => PeriodModel.fromMap(data)).toList();
        debugPrint('成功从SharedPreferences加载 ${records.length} 条经期记录');
        return records;
      }, 'loadPeriodRecords'),
      'DataService.loadPeriodRecords',
      fallbackValue: () => [],
      rethrowError: false
    );
  }

  
  Future<List<PeriodModel>> loadPeriodRecordsByDateRange(DateTime startDate, DateTime endDate) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final allRecords = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
        final formattedStartDate = formatDate(startDate);
        final formattedEndDate = formatDate(endDate);
        
        final filteredRecords = allRecords.where((r) {
          final recordDate = r['start_date'] as String;
          return recordDate.compareTo(formattedStartDate) >= 0 && 
                 recordDate.compareTo(formattedEndDate) <= 0;
        }).toList()..sort((a, b) {
          return (a['start_date'] as String).compareTo(b['start_date'] as String);
        });
        
        final records = filteredRecords.map((data) => PeriodModel.fromMap(data)).toList();
        debugPrint('Loaded ${records.length} period records from SharedPreferences between $startDate and $endDate');
        return records;
      }, 'loadPeriodRecordsByDateRange'),
      'DataService.loadPeriodRecordsByDateRange',
      fallbackValue: () => [],
      rethrowError: true,
    );
  }

  
  Future<PeriodModel?> getPeriodRecordByDate(DateTime date) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final formattedDate = formatDate(date);
        final allRecords = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
        final recordData = allRecords.firstWhere(
          (r) => r['start_date'] == formattedDate,
          orElse: () => <String, dynamic>{}
        );
        
        if (recordData.isNotEmpty) {
          final record = PeriodModel.fromMap(recordData);
          debugPrint('Found period record in SharedPreferences for date: $date');
          return record;
        } else {
          debugPrint('No period record found in SharedPreferences for date: $date');
          return null;
        }
      }, 'getPeriodRecordByDate'),
      'DataService.getPeriodRecordByDate',
    );
  }

  
  Future<void> savePeriodRecord(PeriodModel record) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
        final recordMap = record.toMap();
        final formattedDate = formatDate(record.date);
        recordMap['id'] = recordMap['id'] ?? formattedDate;
        
        final allRecords = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
        final existingIndex = allRecords.indexWhere((r) => r['start_date'] == formattedDate);
        
        if (existingIndex >= 0) {
          allRecords[existingIndex] = recordMap;
          await _prefsService.setObjectList(SharedPreferencesService.keyPeriods, allRecords);
          debugPrint('更新了SharedPreferences中日期为 ${record.date} 的经期记录');
        } else {
          await _prefsService.addObjectToList(SharedPreferencesService.keyPeriods, recordMap);
          debugPrint('在SharedPreferences中创建了日期为 ${record.date} 的经期记录');
        }
        
        if (record.isPeriod) {
          await _updateLastPeriodDateIfNeeded(record.date);
        }
      }, 'savePeriodRecord'),
      'DataService.savePeriodRecord',
      rethrowError: true
    );
  }

  
  Future<void> savePeriodRecords(List<PeriodModel> records) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      
      
      await db.transaction((txn) async {
        for (final record in records) {
          final recordData = record.toMap();
          await txn.insert(
            DatabaseHelper.tablePeriod,
            recordData,
            conflictAlgorithm: ConflictAlgorithm.replace,
          );
        }
      });
      
      debugPrint('Saved ${records.length} period records successfully in transaction');
      
      
      await _processPeriodRecordsBatch(records);
      }, 'savePeriodRecords'),
      'DataService.savePeriodRecords',
      rethrowError: true,
    );
  }
  
  
  Future<void> updatePeriodRecord(PeriodModel record) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      final formattedDate = formatDate(record.date);
      final recordMap = record.toMap();
      
      final rowsAffected = await db.update(
        DatabaseHelper.tablePeriod,
        recordMap,
        where: '${DatabaseHelper.columnPeriodStart} = ?',
        whereArgs: [formattedDate]
      );
      
      if (rowsAffected == 0) {
        throw Exception('No period record found to update for date: $formattedDate');
      }
      
      debugPrint('Updated period record for date: $formattedDate');
      
      
      if (record.isPeriod) {
        await _updateLastPeriodDateIfNeeded(record.date);
      }
      }, 'updatePeriodRecord'),
      'DataService.updatePeriodRecord',
      rethrowError: true,
    );
  }

  
  Future<bool> deletePeriodRecord(DateTime date) async {
    return _errorHandler.safeOperation(
      () async {
        final normalizedDate = DateTime(date.year, date.month, date.day);
        final formattedDate = formatDate(normalizedDate);
        
        final allRecords = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
        final initialLength = allRecords.length;
        final updatedRecords = allRecords.where((r) => r['start_date'] != formattedDate).toList();
        
        if (initialLength == updatedRecords.length) {
          debugPrint('尝试删除SharedPreferences中不存在的经期记录: $normalizedDate');
          return false;
        }
        
        await _prefsService.setObjectList(SharedPreferencesService.keyPeriods, updatedRecords);
        debugPrint('成功从SharedPreferences中删除日期为 $normalizedDate 的经期记录');
        
        final userProfile = await loadUserProfile();
        if (userProfile != null && userProfile.lastPeriodDate.isAtSameMomentAs(normalizedDate)) {
          final recentRecords = await getRecentPeriodRecords(limit: 10);
          if (recentRecords.isNotEmpty) {
            final updatedProfile = userProfile.copyWith(lastPeriodDate: recentRecords.first.date);
            await saveUserProfile(updatedProfile);
          }
        }
        
        return true;
      },
      'DataService.deletePeriodRecord',
      fallbackValue: () => false,
      rethrowError: false,
    );
  }
  
  
  Future<void> deletePeriodRecords(List<DateTime> dates) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      final formattedDates = dates.map((date) => formatDate(date)).toList();
      
      
      await db.transaction((txn) async {
        for (final date in formattedDates) {
          await txn.delete(
            DatabaseHelper.tablePeriod,
            where: '${DatabaseHelper.columnPeriodStart} = ?',
            whereArgs: [date]
          );
        }
      });
      
      debugPrint('Batch deleted ${dates.length} period records');
      
      
      final userProfile = await loadUserProfile();
      if (userProfile != null) {
        bool lastPeriodDeleted = dates.any((date) => date.isAtSameMomentAs(userProfile.lastPeriodDate));
        if (lastPeriodDeleted) {
          final recentRecords = await getRecentPeriodRecords(limit: 10);
          if (recentRecords.isNotEmpty) {
            final updatedProfile = userProfile.copyWith(lastPeriodDate: recentRecords.first.date);
            await saveUserProfile(updatedProfile);
          }
        }
      }
      }, 'deletePeriodRecords'),
      'DataService.deletePeriodRecords',
      rethrowError: true,
    );
  }
  
  
  Future<void> clearPeriodRecords() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      await db.delete(DatabaseHelper.tablePeriod);
      debugPrint('All period records cleared');
      }, 'clearPeriodRecords'),
      'DataService.clearPeriodRecords',
      rethrowError: true,
    );
  }

  
  Future<Map<String, dynamic>> loadAppSettings() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      final result = await db.query(DatabaseHelper.tableUserSettings);
      
      final settings = <String, dynamic>{};
      for (final setting in result) {
        final key = setting[DatabaseHelper.columnSettingsKey] as String;
        final value = setting[DatabaseHelper.columnSettingsValue];
        settings[key] = value;
      }
      
      debugPrint('Loaded ${settings.length} app settings');
      return settings;
      }, 'loadAppSettings'),
      'DataService.loadAppSettings',
      fallbackValue: () => {},
      rethrowError: true,
    );
  }

  
  Future<void> saveAppSetting(String key, dynamic value) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final settings = _prefsService.getObjectList(SharedPreferencesService.keyUserSettings);
      final settingIndex = settings.indexWhere((s) => s['key'] == key);
      
      final settingData = {
        'key': key,
        'value': value.toString(),
        'updatedAt': DateTime.now().toIso8601String(),
      };
      
      if (settingIndex >= 0) {
        settings[settingIndex] = settingData;
      } else {
        settings.add(settingData);
      }
      
      await _prefsService.setObjectList(SharedPreferencesService.keyUserSettings, settings);
      debugPrint('Saved app setting to SharedPreferences: $key = $value');
    }, 'saveAppSetting'),
      'DataService.saveAppSetting',
      rethrowError: true,
    );
  }

  
  Future<void> saveAppSettings(Map<String, dynamic> settings) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      
      
      await db.transaction((txn) async {
        for (final entry in settings.entries) {
          await txn.insert(
            DatabaseHelper.tableUserSettings,
            {
              DatabaseHelper.columnSettingsKey: entry.key,
              DatabaseHelper.columnSettingsValue: entry.value.toString(),
              'updatedAt': DateTime.now().toIso8601String(),
            },
            conflictAlgorithm: ConflictAlgorithm.replace,
          );
        }
      });
      
      debugPrint('Saved ${settings.length} app settings in transaction');
      }, 'saveAppSettings'),
      'DataService.saveAppSettings',
      rethrowError: true,
    );
  }

  
  Future<List<Map<String, dynamic>>> loadUserRecords(String recordType) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      final result = await db.query(
        DatabaseHelper.tableKnowledge,
        where: 'recordType = ?',
        whereArgs: [recordType],
        orderBy: 'date DESC',
      );
      
      debugPrint('Loaded ${result.length} user records of type: $recordType');
      return result;
      }, 'loadUserRecords'),
      'DataService.loadUserRecords',
      fallbackValue: () => [],
      rethrowError: true,
    );
  }

  

  
  Future<void> updateUserRecord(Map<String, dynamic> recordData) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      
      final result = await db.update(
        DatabaseHelper.tableKnowledge,
        recordData,
        where: 'id = ?',
        whereArgs: [1],
      );
      
      if (result == 0) {
        // 如果没有找到记录，则插入新记录
        await saveUserRecord(recordData);
      }
      
      debugPrint('Updated user record');
      }, 'updateUserRecord'),
      'DataService.updateUserRecord',
      rethrowError: true,
    );
  }
  
  Future<void> saveUserRecord(Map<String, dynamic> record) async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      
      
      final recordWithTimestamp = Map<String, dynamic>.from(record);
      if (!recordWithTimestamp.containsKey('createdAt')) {
          recordWithTimestamp['createdAt'] = 
              DateTime.now().toIso8601String();
        }
      
      await db.insert(
        DatabaseHelper.tableKnowledge,
        recordWithTimestamp,
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
      
      debugPrint('Saved user record successfully');
      }, 'saveUserRecord'),
      'DataService.saveUserRecord',
      rethrowError: true,
    );
  }

  
  Future<void> clearAllData() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      await _prefsService.remove(SharedPreferencesService.keyUser);
      await _prefsService.remove(SharedPreferencesService.keyPeriods);
      await _prefsService.remove(SharedPreferencesService.keyKnowledge);
      await _prefsService.remove(SharedPreferencesService.keyUserSettings);
      debugPrint('All data cleared successfully from SharedPreferences');
      }, 'clearAllData'),
      'DataService.clearAllData',
      rethrowError: true,
    );
  }

  
  Future<Map<String, int>> getDatabaseStats() async {
    return _errorHandler.safeOperation(
      () => _withRetry(() async {
      final db = await _databaseHelper.database;
      
      final userProfileCount = Sqflite.firstIntValue(
          await db.rawQuery('SELECT COUNT(*) FROM ${DatabaseHelper.tableUser}')
        ) ?? 0;
      
      final periodRecordsCount = Sqflite.firstIntValue(
        await db.rawQuery('SELECT COUNT(*) FROM ${DatabaseHelper.tablePeriod}')
      ) ?? 0;
      
      final periodDaysCount = Sqflite.firstIntValue(
        await db.rawQuery(
          'SELECT COUNT(*) FROM ${DatabaseHelper.tablePeriod} ' 
          'WHERE ${DatabaseHelper.columnPeriodFlow} IS NOT NULL'
        )
      ) ?? 0;
      
      final userRecordsCount = Sqflite.firstIntValue(
          await db.rawQuery('SELECT COUNT(*) FROM ${DatabaseHelper.tableKnowledge}')
        ) ?? 0;
        
        final appSettingsCount = Sqflite.firstIntValue(
          await db.rawQuery('SELECT COUNT(*) FROM ${DatabaseHelper.tableUserSettings}')
        ) ?? 0;
      
      return {
        'userProfiles': userProfileCount,
        'periodRecords': periodRecordsCount,
        'periodDays': periodDaysCount,
        'userRecords': userRecordsCount,
        'appSettings': appSettingsCount,
      };
      }, 'getDatabaseStats'),
      'DataService.getDatabaseStats',
      fallbackValue: () => {
        'userProfiles': 0,
        'periodRecords': 0,
        'periodDays': 0,
        'userRecords': 0,
        'appSettings': 0,
      },
      rethrowError: true,
    );
  }

  
  Future<bool> updateCycleSettings({
    required int cycleLength,
    required int periodLength,
    DateTime? lastPeriodDate,
  }) async {
    return _errorHandler.safeOperation(
      () async {
        
        if (cycleLength < 21 || cycleLength > 45) {
          throw _errorHandler.createValidationError('周期长度必须在21-45天之间');
        }
        if (periodLength < 1 || periodLength > 10) {
          throw _errorHandler.createValidationError('经期长度必须在1-10天之间');
        }
        
        
        if (cycleLength <= periodLength) {
          throw _errorHandler.createValidationError('周期长度必须大于经期长度');
        }
        
        final existingProfile = await loadUserProfile();
        if (existingProfile == null) {
          if (lastPeriodDate == null) {
            throw _errorHandler.createValidationError('创建新用户档案时，必须提供最后经期日期');
          }
          
          
          final newProfile = UserProfile(
            id: null,
            name: '默认用户',
            birthDate: DateTime.now().subtract(Duration(days: 25 * 365)),
            height: 160,
            weight: 55,
            bloodType: 'A',
            cycleLength: cycleLength,
            periodLength: periodLength,
            lastPeriodDate: lastPeriodDate,
            currentMode: 'standard',
            notificationsEnabled: true,
            darkMode: false,
          );
          await saveUserProfile(newProfile);
          debugPrint('创建新用户档案并设置周期参数: 周期长度=$cycleLength, 经期长度=$periodLength');
          return true;
        } else {
          
          bool hasChanges = cycleLength != existingProfile.cycleLength ||
                           periodLength != existingProfile.periodLength ||
                           (lastPeriodDate != null && lastPeriodDate != existingProfile.lastPeriodDate);
          
          if (hasChanges) {
            final updatedProfile = existingProfile.copyWith(
              cycleLength: cycleLength,
              periodLength: periodLength,
              lastPeriodDate: lastPeriodDate ?? existingProfile.lastPeriodDate,
            );
            
            await saveUserProfile(updatedProfile);
            debugPrint('更新周期设置: 周期长度=$cycleLength, 经期长度=$periodLength');
          }
          return hasChanges;
        }
      },
      'DataService.updateCycleSettings',
      fallbackValue: () => false,
      rethrowError: true,
    );
  }

  
  Future<Map<String, dynamic>> getCycleSettings() async {
    return _errorHandler.safeOperation(
      () async {
        
        final userProfile = await loadUserProfile();
        if (userProfile != null) {
          return {
            'cycleLength': userProfile.cycleLength,
            'periodLength': userProfile.periodLength,
            'lastPeriodDate': userProfile.lastPeriodDate,
            'hasProfile': true,
          };
        } else {
          
          return {
            'cycleLength': 28,
            'periodLength': 5,
            'lastPeriodDate': null,
            'hasProfile': false,
          };
        }
      },
      'DataService.getCycleSettings',
      fallbackValue: () => {
        'cycleLength': 28,
        'periodLength': 5,
        'lastPeriodDate': null,
        'hasProfile': false,
      },
      rethrowError: false,
    );
  }

  
  Future<void> saveCycleHistory(CycleInfo cycleInfo) async {
    try {
      final historyMap = {
        'cycleId': DateTime.now().millisecondsSinceEpoch,
        'startDate': cycleInfo.nextPeriodDate.toIso8601String(),
        'endDate': cycleInfo.nextPeriodDate.add(Duration(days: cycleInfo.periodLength - 1)).toIso8601String(),
        'cycleLength': cycleInfo.cycleLength,
        'periodLength': cycleInfo.periodLength,
        'ovulationDate': cycleInfo.ovulationDate.toIso8601String(),
        'recordedAt': DateTime.now().toIso8601String(),
      };
      
      // 保存到数据库，指定记录类型
      await saveUserRecord({
        ...historyMap,
        'recordType': 'cycle_history'
      });
      
      debugPrint('Saved cycle history successfully');
    } catch (e) {
      debugPrint('Failed to save cycle history: $e');
      
    }
  }

  
  Future<List<PeriodModel>> getRecentPeriodRecords({int limit = 10}) async {
    try {
      final allRecords = _prefsService.getObjectList(SharedPreferencesService.keyPeriods);
      final periodRecords = allRecords
        .where((r) => r['flow'] != null)
        .toList()
        ..sort((a, b) {
          final dateA = DateTime.parse(a['start_date'] as String);
          final dateB = DateTime.parse(b['start_date'] as String);
          return dateB.compareTo(dateA); // 降序排序
        });
      
      final limitedRecords = periodRecords.take(limit).toList();
      final records = limitedRecords.map((data) => PeriodModel.fromMap(data)).toList();
      debugPrint('Loaded ${records.length} recent period records from SharedPreferences');
      return records;
    } catch (e) {
      debugPrint('Failed to get recent period records from SharedPreferences: $e');
      return [];
    }
  }

  
  Future<CycleInfo> calculateAndSaveCycleInfo() async {
    try {
      
      final predictionService = ServiceLocator().get<PredictionService>();
      final userProfile = await loadUserProfile();
      
      if (userProfile == null) {
        throw Exception('用户档案不存在');
      }
      
      
      final predictionResult = await predictionService.predictCycle(userProfile, forceRecalculate: true);
      
      
      final daysUntilNextPeriod = predictionResult.nextPeriodDate.difference(DateTime.now()).inDays;
      final daysUntilOvulation = predictionResult.ovulationDate.difference(DateTime.now()).inDays;
      
      
      final cycleInfo = CycleInfo(
        cycleLength: userProfile.cycleLength,
        periodLength: userProfile.periodLength,
        nextPeriodDate: predictionResult.nextPeriodDate,
        ovulationDate: predictionResult.ovulationDate,
        pregnancyRate: daysUntilOvulation.abs() <= 3 ? 0.85 : 0.05,
        daysUntilNextPeriod: daysUntilNextPeriod,
        daysUntilOvulation: daysUntilOvulation,
        healthScore: 85, 

        healthStatus: '良好',
        fertilityWindow: daysUntilOvulation.abs() <= 5 ? '受孕窗口期' : '非受孕窗口期',
        recommendations: _generateRecommendations(userProfile, 85),
      );

      
      await saveAppSetting('next_period_date', predictionResult.nextPeriodDate.toIso8601String());
      await saveAppSetting('ovulation_date', predictionResult.ovulationDate.toIso8601String());
      await saveAppSetting('health_score', '85');
      await _savePredictionResults(cycleInfo, userProfile);

      debugPrint('使用高级预测服务计算并保存周期信息');
      return cycleInfo;
    } catch (e) {
      debugPrint('使用高级预测服务计算周期信息失败，回退到基础算法: $e');
      rethrow;
    }
  }
  
  
  Future<void> _savePredictionResults(CycleInfo cycleInfo, UserProfile userProfile) async {
    try {
      
      final validUntil = cycleInfo.nextPeriodDate.add(Duration(days: 7));
      
      
      final predictions = <Map<String, dynamic>>[];
      final nowTimestamp = DateTime.now().millisecondsSinceEpoch;
      
      
      predictions.add({
        'date': formatDate(cycleInfo.nextPeriodDate),
        'type': 'period',
        'confidence': 0.85, 

        'validUntil': DateUtils.formatDate(validUntil),
        'createdAt': nowTimestamp,
      });
      
      
        predictions.add({
          'date': DateUtils.formatDate(cycleInfo.ovulationDate),
          'type': 'ovulation',
          'confidence': 0.75, 

          'validUntil': DateUtils.formatDate(validUntil),
          'createdAt': nowTimestamp,
        });
        final ovulationDate = cycleInfo.ovulationDate;
        final fertileWindowStart = ovulationDate.subtract(Duration(days: 3));
        final fertileWindowEnd = ovulationDate.add(Duration(days: 2));
        
        for (var date = fertileWindowStart; 
             !date.isAfter(fertileWindowEnd); 
             date = date.add(Duration(days: 1))) {
          
          final dayDiff = date.difference(ovulationDate).inDays.abs();
          final confidence = 0.9 - (dayDiff * 0.05); 

          
          predictions.add({
            'date': formatDate(date),
            'type': 'fertile',
            'confidence': confidence,
            'validUntil': DateUtils.formatDate(validUntil),
          'createdAt': nowTimestamp,
          });
        }
      
      for (final prediction in predictions) {
        await saveUserRecord({
          ...prediction,
          'recordType': 'prediction'
        });
      }
      
      developer.log('预测结果保存成功，共 ${predictions.length} 条');
    } catch (e) {
      developer.log('保存预测结果失败: $e');
      
    }
  }

  
  Future<List<Map<String, dynamic>>> getValidPredictions({String? type}) async {
    try {
      final db = await _databaseHelper.database;
      final today = formatDate(DateTime.now());
      
      
      final whereClause = type != null 
        ? 'recordType = ? AND validUntil >= ? AND type = ?' 
        : 'recordType = ? AND validUntil >= ?';
      final whereArgs = type != null 
        ? ['prediction', today, type]
        : ['prediction', today];
      
      final result = await db.query(
        DatabaseHelper.tableKnowledge,
        where: whereClause,
        whereArgs: whereArgs,
        orderBy: 'date ASC',
      );
      
      developer.log('获取到 ${result.length} 条有效预测');
      return result;
    } catch (e) {
      developer.log('获取预测结果失败: $e');
      return [];
    }
  }

  
  Future<List<Map<String, dynamic>>> getPredictionsByDateRange(DateTime startDate, DateTime endDate) async {
    try {
      final db = await _databaseHelper.database;
      final formattedStartDate = formatDate(startDate);
      final formattedEndDate = formatDate(endDate);
      final today = formatDate(DateTime.now());
      
      final result = await db.query(
        DatabaseHelper.tableKnowledge,
        where: 'recordType = ? AND date BETWEEN ? AND ? AND validUntil >= ?',
        whereArgs: ['prediction', formattedStartDate, formattedEndDate, today],
        orderBy: 'date ASC',
      );
      
      developer.log('获取到日期范围内 ${result.length} 条预测');
      return result;
    } catch (e) {
      developer.log('获取日期范围内的预测失败: $e');
      return [];
    }
  }

  
  Future<void> refreshPredictions() async {
    try {
      
      // 先跳过这个调用，因为该方法可能不存在
      
      
      final db = await _databaseHelper.database;
      final today = formatDate(DateTime.now());
      await db.delete(
        DatabaseHelper.tableKnowledge,
        where: 'recordType = ? AND validUntil < ?',
        whereArgs: ['prediction', today],
      );
      
      developer.log('预测结果刷新成功');
    } catch (e) {
      developer.log('刷新预测失败: $e');
      throw Exception('刷新预测失败: $e');
    }
  }

  
  List<String> _generateRecommendations(UserProfile profile, int healthScore) {
    final recommendations = <String>[];
    
    if (healthScore < 60) {
      recommendations.add('建议咨询医生，关注周期规律性');
    }
    
    if (profile.age < 18 || profile.age > 45) {
      recommendations.add('注意年龄相关的生理变化');
    }
    
    if (profile.isUsingBirthControl) {
      recommendations.add('注意避孕药对周期的影响');
    }
    
    if (recommendations.isEmpty) {
      recommendations.add('保持规律的作息和健康的生活方式');
    }
    
    return recommendations;
  }
}